<template>
  <view class="violation-list-container">
    <!-- 顶部筛选区 -->
    <view class="filter-section">
      <view class="filter-row">
        <view class="filter-item">
          <picker mode="date" :value="filterDate" @change="onDateChange">
            <view class="picker-view">
              <text>{{ filterDate || '全部日期' }}</text>
              <text class="picker-icon"></text>
            </view>
          </picker>
        </view>
        <view class="filter-item">
          <select 
            v-model="filterTeacher"
            class="teacher-select"
            @change="onTeacherChange"
          >
            <option value="">全部教师</option>
            <option 
              v-for="teacher in teacherList" 
              :key="teacher.teacherId"
              :value="teacher.teacherName"
            >
              {{ teacher.teacherName }}
              
            </option>
          </select>
        </view>
        <view class="filter-item">
          <input 
            class="search-input" 
            v-model="searchKeyword" 
            placeholder="搜索班级"
            @confirm="searchViolations"
          />
        </view>
        <button class="search-btn" size="mini" type="primary" @click="searchViolations">搜索</button>
      </view>
      <view v-if="filterDate || searchKeyword || filterTeacher" class="filter-tags">
        <text v-if="filterDate" class="filter-tag" @click="clearDateFilter">
          日期: {{ filterDate }} ✕
        </text>
        <text v-if="filterTeacher" class="filter-tag" @click="clearTeacherFilter">
          教师: {{ filterTeacher }} ✕
        </text>
        <text v-if="searchKeyword" class="filter-tag" @click="clearSearchKeyword">
          班级: {{ searchKeyword }} ✕
        </text>
        <text class="clear-all" @click="clearAllFilters">清除全部</text>
      </view>
    </view>

    <!-- 统计信息 -->
    <view class="stats-section">
      <view class="stats-item">
        <text class="stats-number">{{ totalCount }}</text>
        <text class="stats-label">总违纪次数</text>
      </view>
      <view class="stats-item">
        <text class="stats-number">{{ todayCount }}</text>
        <text class="stats-label">今日违纪</text>
      </view>
      <view class="stats-item">
        <text class="stats-number">{{ classCount }}</text>
        <text class="stats-label">违纪班级数</text>
      </view>
    </view>

    <!-- 按班级分组的违纪卡片列表 -->
    <view class="violation-cards">
      <view 
        v-for="(classGroup, index) in groupedByClass" 
        :key="index" 
        class="violation-card"
        @click="viewClassDetail(classGroup)"
      >
        <!-- 卡片头部 -->
        <view class="card-header">
          <view class="header-left">
            <text class="class-name-main">{{ classGroup.className }}</text>
          </view>
          <view class="header-right">
            <text class="arrow-icon">›</text>
          </view>
        </view>

        <!-- 统计信息 -->
        <view class="card-stats">
          <view class="stat-item">
            <text class="stat-label">违纪次数:</text>
            <text class="stat-value">{{ classGroup.totalCount }}次</text>
          </view>
          <view class="stat-item">
            <text class="stat-label">今日违纪:</text>
            <text class="stat-value highlight">{{ classGroup.todayCount }}次</text>
          </view>
        </view>

        <!-- 最近一次违纪信息 -->
        <view class="card-footer">
          <text class="recent-info">最近: {{ classGroup.latestDate }} {{ classGroup.latestCourse }}</text>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="groupedByClass.length === 0 && !loading" class="empty-state">
        <text class="empty-icon">📋</text>
        <text class="empty-text">暂无违纪记录</text>
      </view>

      <!-- 加载中 -->
      <view v-if="loading" class="loading-state">
        <text>加载中...</text>
      </view>
    </view>
  </view>
</template>

<script>
  import config from '@/config'
  
  export default {
    data() {
      return {
        violationList: [], // 原始违纪列表
        groupedByClass: [], // 按班级分组后的数据
        filterDate: '', // 默认不设置日期,查询所有
        filterTeacher: '', // 教师筛选
        searchKeyword: '',
        loading: false,
        totalCount: 0,
        todayCount: 0,
        classCount: 0, // 违纪班级数
        classroomMap: {}, // 教室ID -> 教室信息(仅用于补充显示)
        teacherList: [] // 教师列表
      }
    },
    onLoad() {
      // 初始化数据
      this.initData()
    },
    methods: {
      // 去除班级名称前导0
      removeLeadingZeros(className) {
        // 1. 去除开头的0: "0高技2404班" -> "高技2404班"
        // 2. 去除数字中的前导0: "0210" -> "210"
        let result = className.replace(/^0+([^0])/g, '$1')  // 去除开头的0
        result = result.replace(/(\D)0+(\d)/g, '$1$2')  // 去除非数字后的0
        return result
      },
      // 初始化数据
      async initData() {
        // 先加载教室数据,再加载违纪数据
        await this.loadTeacherList()
        await this.loadClassroomData()
        // loadClassroomData 内部已经调用了 loadViolations
      },
      
      // 初始化日期为今天
      initDate() {
        const today = new Date()
        const year = today.getFullYear()
        const month = String(today.getMonth() + 1).padStart(2, '0')
        const day = String(today.getDate()).padStart(2, '0')
        this.filterDate = `${year}-${month}-${day}`
      },
      
      // 加载教师列表（从课表中获取）
      async loadTeacherList() {
        try {
          const token = uni.getStorageSync('App-Token')
          
          // 从课表获取教师列表（需要从班级课表和实训室课表两个API获取）
          let allTeachers = new Set()
          
          // 1. 从班级课表获取
          await this.fetchTeachersFromSchedule(
            config.baseUrl + '/admin-api/ao/vocational-class-schedule/page',
            token,
            allTeachers,
            'class'
          )
          
          // 2. 从实训室课表获取
          await this.fetchTeachersFromSchedule(
            config.baseUrl + '/admin-api/ao/lab-schedule/page',
            token,
            allTeachers,
            'lab'
          )
          
          // console.log('提取到的教师数量:', allTeachers.size)
          
          // 转换为数组并排序
          this.teacherList = Array.from(allTeachers)
            .map((name, index) => ({
              teacherId: index + 1,
              teacherName: name
            }))
            .sort((a, b) => {
              return a.teacherName.localeCompare(b.teacherName, 'zh-CN')
            })
            
        } catch (err) {
          console.error('加载教师列表失败:', err)
        }
      },
      
      // 从课表API中提取教师名称
      async fetchTeachersFromSchedule(url, token, teachersSet, type) {
        let pageNo = 1
        const pageSize = 100
        let hasMore = true
        let totalRecords = 0
        
        while (hasMore) {
          const response = await uni.request({
            url: url,
            method: 'GET',
            header: {
              'Authorization': 'Bearer ' + token,
              'tenant-id': '1',
              'Content-Type': 'application/json'
            },
            data: {
              pageNo: pageNo,
              pageSize: pageSize
            }
          })
          
          const [error, res] = response
          
          if (!error && res.data && res.data.code === 0 && res.data.data) {
            const list = res.data.data.list || []
            totalRecords += list.length
            
            // 从每条课表记录中提取教师名称
            list.forEach(schedule => {
              // 遍历周一到周日的课程字段
              const dayFields = type === 'class' 
                ? ['mondayCourse', 'tuesdayCourse', 'wednesdayCourse', 'thursdayCourse', 'fridayCourse', 'saturdayCourse', 'sundayCourse']
                : ['mondayUsage', 'tuesdayUsage', 'wednesdayUsage', 'thursdayUsage', 'fridayUsage', 'saturdayUsage', 'sundayUsage']
              
              dayFields.forEach(field => {
                const courseInfo = schedule[field]
                if (courseInfo && courseInfo.trim()) {
                  // 解析课程信息
                  const lines = courseInfo.split(/[\r\n]+/).filter(line => line.trim())
                  
                  if (type === 'class' && lines.length >= 2) {
                    // 班级课表格式: "课程名\r\n教师名\r\n场地名"
                    const teacherName = lines[1].trim()
                    if (teacherName) {
                      teachersSet.add(teacherName)
                    }
                  } else if (type === 'lab' && lines.length >= 2) {
                    // 实训室课表格式: "年级+班级\r\n课程名 教师名"
                    const courseAndTeacher = lines[1] || ''
                    const parts = courseAndTeacher.split(/\s+/).filter(p => p.trim())
                    if (parts.length >= 2) {
                      const teacherName = parts.slice(1).join(' ').trim()
                      if (teacherName) {
                        teachersSet.add(teacherName)
                      }
                    }
                  }
                }
              })
            })
            
            const total = res.data.data.total || 0
            if (list.length < pageSize || totalRecords >= total) {
              hasMore = false
            } else {
              pageNo++
            }
          } else {
            hasMore = false
          }
        }
        
        // console.log(`${type === 'class' ? '班级课表' : '实训室课表'}记录数:`, totalRecords)
      },
      
      // 加载教室数据(用于补充没有班级信息的旧数据)
      async loadClassroomData() {
        try {
          // 获取token
          const token = uni.getStorageSync('App-Token')
          
          // 加载教室位置数据(用于补充显示)
          const classroomRes = await uni.request({
            url: config.baseUrl + '/admin-api/ao/class-location/page',
            method: 'GET',
            header: {
              'Authorization': 'Bearer ' + token,
              'tenant-id': '1',
              'Content-Type': 'application/json'
            },
            data: {
              pageNo: 1,
              pageSize: 500
            }
          })
          
          // 解析教室数据
          let classroomList = []
          if (classroomRes[1] && classroomRes[1].data) {
            const resData = classroomRes[1].data
            if (resData.code === 0 && resData.data && resData.data.list) {
              classroomList = resData.data.list
            }
          }
          
          classroomList.forEach(room => {
            this.classroomMap[room.id] = {
              name: room.classroomName,
              building: room.building,
              floor: room.floor
            }
          })
          
          // 加载违纪数据
          this.loadViolations()
        } catch (err) {
          console.error('加载教室数据失败:', err)
          uni.showToast({
            title: '数据加载失败',
            icon: 'none'
          })
        }
      },

      // 加载违纪记录
      async loadViolations() {
        this.loading = true
        try {
          // 获取token
          const token = uni.getStorageSync('App-Token')
          
          // 构建请求参数
          const params = {
            pageNo: 1,
            pageSize: 100
          }
          
          // 日期参数需要转换为日期范围数组 [开始日期, 结束日期]
          if (this.filterDate) {
            // 如果选择了日期,查询当天的数据
            // 后端需要的格式: ['2025-10-14 00:00:00', '2025-10-14 23:59:59']
            params.classDate = [
              `${this.filterDate} 00:00:00`,
              `${this.filterDate} 23:59:59`
            ]
          }
          
          // 教师筛选参数
          if (this.filterTeacher) {
            params.teacherName = this.filterTeacher
          }
          
          const res = await uni.request({
            url: config.baseUrl + '/admin-api/ao/patrol/page',
            method: 'GET',
            header: {
              'Authorization': 'Bearer ' + token,
              'tenant-id': '1',
              'Content-Type': 'application/json'
            },
            data: params
          })

          // 解析违纪数据
          let violationData = { list: [], total: 0 }
          if (res[1] && res[1].data) {
            const resData = res[1].data
            if (resData.code === 0 && resData.data) {
              violationData = resData.data
            }
          }

          // 自动删除"无违纪"记录
          if (violationData.list && violationData.list.length > 0) {
            const noViolationRecords = violationData.list.filter(item => 
              item.violationType === '无违纪' || item.violationCount === 0
            )
            
            if (noViolationRecords.length > 0) {
              console.log('检测到', noViolationRecords.length, '条无违纪记录，正在删除...')
              // 批量删除无违纪记录
              for (const record of noViolationRecords) {
                try {
                  await uni.request({
                    url: config.baseUrl + `/admin-api/ao/patrol/delete?id=${record.id}`,
                    method: 'DELETE',
                    header: {
                      'Authorization': 'Bearer ' + token,
                      'tenant-id': '1'
                    }
                  })
                } catch (err) {
                  console.error('删除无违纪记录失败:', record.id, err)
                }
              }
              console.log('无违纪记录删除完成')
            }
          }

          if (violationData.list && violationData.list.length > 0) {
            // 处理数据,优先使用数据库中的班级名称
            // 同时过滤掉"无违纪"记录
            this.violationList = violationData.list
              .filter(item => {
                // 过滤条件: 排除"无违纪"记录
                return item.violationType !== '无违纪' && item.violationCount > 0
              })
              .map(item => {
                const classroom = this.classroomMap[item.classroomId] || {}
                
                return {
                  ...item,
                  // 优先使用数据库保存的班级名称,如果没有则显示"未知班级"
                  className: item.className || '未知班级',
                  // 优先使用数据库的教室名,如果没有则用教室ID查找
                  classroomName: item.classroom || classroom.name || `教室${item.classroomId}`
                }
              })

            this.totalCount = this.violationList.length  // 使用过滤后的数量

            // 统计今日违纪数
            const today = new Date()
            const todayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
            this.todayCount = this.violationList.filter(item => 
              item.classDate === todayStr
            ).length
            
            // 按班级分组
            this.groupViolationsByClass()
          } else {
            this.violationList = []
            this.groupedByClass = []
            this.totalCount = 0
            this.todayCount = 0
            this.classCount = 0
          }
        } catch (err) {
          console.error('加载违纪记录失败:', err)
          uni.showToast({
            title: '加载失败',
            icon: 'none'
          })
        } finally {
          this.loading = false
        }
      },

      // 日期选择
      onDateChange(e) {
        this.filterDate = e.detail.value
        this.loadViolations()
      },
      
      // 教师选择
      onTeacherChange() {
        this.loadViolations()
      },
      
      // 搜索按钮点击
      searchViolations() {
        // 如果有搜索关键词,只需要重新分组(前端过滤)
        if (this.searchKeyword && !this.filterDate && !this.filterTeacher) {
          this.groupViolationsByClass()
        } else {
          // 如果修改了日期或清空了关键词,需要重新加载数据
          this.loadViolations()
        }
      },
      
      // 清除日期筛选
      clearDateFilter() {
        this.filterDate = ''
        this.loadViolations()
      },
      
      // 清除教师筛选
      clearTeacherFilter() {
        this.filterTeacher = ''
        this.loadViolations()
      },
      
      // 清除搜索关键词
      clearSearchKeyword() {
        this.searchKeyword = ''
        this.groupViolationsByClass()
      },
      
      // 清除所有筛选
      clearAllFilters() {
        this.filterDate = ''
        this.filterTeacher = ''
        this.searchKeyword = ''
        this.loadViolations()
      },

      // 按班级分组违纪记录
      groupViolationsByClass() {
        const classMap = new Map()
        const today = new Date()
        const todayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
        
        // 先过滤搜索关键词
        let filteredList = this.violationList
        if (this.searchKeyword && this.searchKeyword.trim()) {
          const keyword = this.searchKeyword.trim().toLowerCase()
          filteredList = this.violationList.filter(item => {
            const originalClassName = item.className || ''
            const displayClassName = this.removeLeadingZeros(originalClassName)
            // 同时搜索原始班级名和显示班级名
            return originalClassName.toLowerCase().includes(keyword) || 
                   displayClassName.toLowerCase().includes(keyword)
          })
        }
        
        // 按班级分组
        filteredList.forEach(item => {
          // 获取班级名称并去掉开头的"0"
          const originalClassName = item.className || '未知班级'
          let displayClassName = originalClassName
          if (originalClassName !== '未知班级') {
            displayClassName = this.removeLeadingZeros(originalClassName)
          }
          
          if (!classMap.has(displayClassName)) {
            classMap.set(displayClassName, {
              className: displayClassName,  // 显示用的班级名（去除0）
              originalClassName: originalClassName,  // 原始班级名（用于查询）
              records: [],
              totalCount: 0,
              todayCount: 0,
              latestDate: '',
              latestCourse: ''
            })
          }
          
          const classData = classMap.get(displayClassName)
          classData.records.push(item)
          classData.totalCount++
          
          // 统计今日违纪
          if (item.classDate === todayStr) {
            classData.todayCount++
          }
          
          // 记录最近一次违纪信息
          if (!classData.latestDate || item.classDate >= classData.latestDate) {
            classData.latestDate = item.classDate
            classData.latestCourse = item.courseName || '未知课程'
          }
        })
        
        // 转换为数组并按违纪次数排序
        this.groupedByClass = Array.from(classMap.values()).sort((a, b) => {
          // 优先按今日违纪数排序,再按总违纪数排序
          if (b.todayCount !== a.todayCount) {
            return b.todayCount - a.todayCount
          }
          return b.totalCount - a.totalCount
        })
        
        this.classCount = this.groupedByClass.length
        
        // 如果有搜索关键词,更新统计数据为过滤后的结果
        if (this.searchKeyword && this.searchKeyword.trim()) {
          this.totalCount = filteredList.length
          this.todayCount = filteredList.filter(item => item.classDate === todayStr).length
        }
      },

      // 查看班级详情
      viewClassDetail(classGroup) {
        // 跳转到班级违纪详情页，使用原始班级名（带0）进行查询
        uni.navigateTo({
          url: `/pages/patrol/class-violation-detail?className=${encodeURIComponent(classGroup.originalClassName || classGroup.className)}&filterDate=${this.filterDate || ''}`,
          fail: (err) => {
            console.error('跳转失败:', err)
            uni.showToast({
              title: '页面跳转失败',
              icon: 'none'
            })
          }
        })
      },

      // 查看详情
      viewDetail(item) {
        // 可以跳转到详情页或显示弹窗
        uni.showModal({
          title: '违纪详情',
          content: `教室: ${item.classroomName}\n班级: ${item.className}\n课程: ${item.courseName}\n日期: ${item.classDate}\n时间: ${item.classTime}`,
          showCancel: false
        })
      },

      // 获取状态文本
      getStatusText(status) {
        const statusMap = {
          0: '待处理',
          1: '已处理',
          2: '已忽略'
        }
        return statusMap[status] || '未知'
      },

      // 获取状态样式类
      getStatusClass(status) {
        const classMap = {
          0: 'status-pending',
          1: 'status-done',
          2: 'status-ignore'
        }
        return classMap[status] || 'status-pending'
      }
    }
  }
</script>

<style lang="scss" scoped>
  page {
    background-color: #f5f5f5;
  }

  .violation-list-container {
    min-height: 100vh;
    padding-bottom: 20px;
  }

  /* 筛选区 */
  .filter-section {
    background: white;
    padding: 15px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  }

  .filter-row {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .filter-item {
    flex: 1;
  }
  
  /* 调整筛选项宽度比例: 日期 < 教师 < 搜索框 */
  .filter-item:first-child {
    flex: 0.8;
    min-width: 100px;
  }
  
  .filter-item:nth-child(2) {
    flex: 1;
    min-width: 100px;
  }
  
  .filter-item:nth-child(3) {
    flex: 1.2;
  }
  
  .filter-tags {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-top: 10px;
    flex-wrap: wrap;
  }
  
  .filter-tag {
    padding: 4px 10px;
    background: #e3f2fd;
    color: #1976d2;
    border-radius: 12px;
    font-size: 12px;
    cursor: pointer;
  }
  
  .filter-tag:active {
    opacity: 0.7;
  }
  
  .clear-all {
    padding: 4px 10px;
    background: #ffebee;
    color: #c62828;
    border-radius: 12px;
    font-size: 12px;
    cursor: pointer;
  }
  
  .clear-all:active {
    opacity: 0.7;
  }

  .picker-view {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 12px;
    background: #f5f5f5;
    border-radius: 6px;
    font-size: 14px;
    min-height: 40px;
  }

  .picker-icon {
    font-size: 16px;
  }

  .search-input {
    padding: 10px 12px;
    background: #f5f5f5;
    border-radius: 6px;
    font-size: 14px;
    height: 40px;
    box-sizing: border-box;
  }
  
  .teacher-select {
    width: 100%;
    padding: 10px 12px;
    background: #f5f5f5;
    border: none;
    border-radius: 6px;
    font-size: 14px;
    height: 40px;
    box-sizing: border-box;
    color: #333;
  }
  
  .teacher-select:focus {
    background: #fff;
    outline: none;
  }

  .search-btn {
    flex-shrink: 0;
    padding: 0 15px;
    height: 40px;
    line-height: 40px;
    font-size: 14px;
  }

  /* 统计信息 */
  .stats-section {
    display: flex;
    background: white;
    margin: 10px 15px;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  }

  .stats-item {
    flex: 1;
    padding: 20px 10px;
    text-align: center;
    display: flex;
    flex-direction: column;
    gap: 5px;
  }

  .stats-item:not(:last-child) {
    border-right: 1px solid #f0f0f0;
  }

  .stats-number {
    font-size: 28px;
    font-weight: bold;
    color: #667eea;
  }

  .stats-label {
    font-size: 13px;
    color: #999;
  }

  /* 违纪卡片列表 */
  .violation-cards {
    padding: 0 15px;
  }

  .violation-card {
    background: white;
    border-radius: 12px;
    margin-bottom: 15px;
    padding: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
  }

  .violation-card:active {
    transform: scale(0.98);
  }

  /* 卡片头部 */
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding-bottom: 10px;
    border-bottom: 1px solid #f0f0f0;
  }

  .header-left {
    flex: 1;
  }

  .class-name-main {
    font-size: 20px;
    font-weight: bold;
    color: #333;
  }

  .header-right {
    flex-shrink: 0;
    display: flex;
    align-items: center;
  }

  .arrow-icon {
    font-size: 32px;
    color: #999;
    font-weight: 300;
  }

  /* 卡片统计信息 */
  .card-stats {
    display: flex;
    gap: 20px;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
  }

  .stat-item {
    display: flex;
    align-items: center;
    gap: 5px;
  }

  .stat-label {
    font-size: 13px;
    color: #666;
  }

  .stat-value {
    font-size: 15px;
    font-weight: bold;
    color: #333;
  }

  .stat-value.highlight {
    color: #f57c00;
  }

  /* 卡片底部 */
  .card-footer {
    padding-top: 10px;
  }

  .recent-info {
    font-size: 12px;
    color: #999;
  }

  /* 空状态 */
  .empty-state {
    text-align: center;
    padding: 60px 20px;
  }

  .empty-icon {
    display: block;
    font-size: 60px;
    margin-bottom: 15px;
    opacity: 0.3;
  }

  .empty-text {
    font-size: 14px;
    color: #999;
  }

  /* 加载状态 */
  .loading-state {
    text-align: center;
    padding: 30px;
    color: #999;
    font-size: 14px;
  }
</style>
